import  fcgi.Application;
import  fcgi.Connection;
import  fcgi.Request;

import tango.io.stream.Format;
import tango.text.convert.Layout;

class MyApp : FastCGIApplication
{
    private vBuffer stdout;
    private vBuffer stderr;
    private static int counter = 0;
    private FastCGIRequest 	req ;

    this (int id, FastCGIRequest request)
    {
        auto layout = new Layout!(char) ();
        
        stdout = new vBuffer(2048, 2048);
        stderr = new vBuffer(2048, 2048);
	req	= request;
    }
    
    int run()
    {
	stdout.clear;
	stderr.clear;
	scope(exit){
		req.stdout.write(stdout.slice);
		if( stderr.length ) {
			req.stderr.write(stderr.slice);
		}
	}
        stdout ("Content-type: text/html\r\n\r\n") ("<head><title>My first page</title></head>");
        stdout ("<body>");

        // some counters
        synchronized
            counter++;
        stdout ("<h1> Hello world </h1><br>") ("Request #") (counter) (", Thread #") (id) ("<br><br>\n");

        // Write IP
        auto ip = ("REMOTE_ADDR" in request.args);
        if (ip)
        {
            stdout ("Your IP is ") (*ip) ("<br><br>\n");
        }
        else
        {
            stdout ("Cannot extract IP :(<br><br>\n");
        }

        // Write stdin
        stdout ("Data: \"");
        while (1)
        {
            char[10] string;
            int rd = request.stdin.read(string);
            if (rd > 0)
                stdout(string[0 .. rd]);
            if (rd != string.length)
            {
                stdout ("\"<br><br>");
                break;
            }
        }

        // Write all arguments
        stdout ("\nYour environment:<br>\n");
        foreach (key, value; request.args)
        {
            stdout ("request.args[\"")(key) ("\"] = \"") (value) ("\"<br>\n");
        }
        stdout ("</body>\n");

        return 0;
    }
}

int main(char[][] args)
{
    FastCGIConnection connection = new FastCGIConnection ("","1983");

    return FastCGIApplication.loop!(MyApp) (connection, true, 10);
}

